package services

import (
	"encoding/json"
	"errors"
	"fmt"
	"lingc/models"
	"lingc/utils"
	"log"
	"strconv"
	"time"

	"gorm.io/gorm"
)

// ChatService 提供账号登录校验的服务
type ChatService struct {
	DB *gorm.DB
}
type UserNickHead struct {
	NickName string `json:"nick_name"`
	HeadImg  string `json:"head_img"`
}

// NewChatService 创建一个新的 ChatService 实例
func NewChatService(db *gorm.DB) *ChatService {
	return &ChatService{DB: db}
}

// GetChatGroupRelationById 获取聊天组关系
func (s *ChatService) GetChatGroupRelationById(group_id uint, user_id uint, user_type string) (*models.ChatGroupRelation, error) {
	var data models.ChatGroupRelation
	if err := s.DB.Where("group_id = ?", group_id).Where("user_id = ?", user_id).Where("user_type = ?", user_type).First(&data).Error; err != nil {
		return nil, errors.New("数据不存在")
	}
	return &data, nil
}

// CreateChatGroup 创建聊天组 如果有聊天组存在则返回聊天组id
func (s *ChatService) CreateChatGroup(admin_id uint, user_id uint, username string) (uint, uint) {

	group_id := utils.GetRedis("chat_group_" + fmt.Sprintf("%d%d", admin_id, user_id))
	if group_id != "" {
		group_id, _ := strconv.Atoi(group_id)
		return uint(group_id), 0
	}
	var existingData models.ChatGroup
	result := s.DB.Where("admin_id = ?", admin_id).Where("user_id = ?", user_id).First(&existingData)
	// log.Printf("数据已存在: %v", existingData)
	if result.Error != nil {
		if result.Error == gorm.ErrRecordNotFound {
			// 数据不存在，创建新数据
			addData := &models.ChatGroup{
				Name:    username,
				AdminID: admin_id,
				UserID:  user_id,
			}
			// 保存到数据库
			if err := s.DB.Create(addData).Error; err != nil {
				return 0, 0
			}
			if err := s.DB.Create(&models.ChatGroupRelation{
				GroupID:  addData.ID,
				UserID:   admin_id,
				UserType: "admin",
			}).Error; err != nil {
				return 0, 0
			}
			if err := s.DB.Create(&models.ChatGroupRelation{
				GroupID:  addData.ID,
				UserID:   user_id,
				UserType: "member",
			}).Error; err != nil {
				return 0, 0
			}
			utils.SetRedis("chat_group_"+fmt.Sprintf("%d%d", admin_id, user_id), fmt.Sprintf("%d", addData.ID), 60*24*346)
			return uint(addData.ID), 1
		}
		// 其他错误
		log.Printf("查询数据库时发生错误: %v", result.Error)
		return 0, 0
	}
	// 数据已存在
	// log.Printf("数据已存在: %v", existingData)
	utils.SetRedis("chat_group_"+fmt.Sprintf("%d%d", admin_id, user_id), fmt.Sprintf("%d", existingData.ID), 60*24*346)
	return uint(existingData.ID), 0
}

// GetGroupIds 获取聊天组id
// GetGroupIds 获取聊天组id
func (s *ChatService) GetGroupIds(groud_id uint) map[string]uint {
	var ids = make(map[string]uint) // 初始化 map
	ids_str := utils.GetRedis("chat_group_ids_" + fmt.Sprintf("%d", groud_id))
	if ids_str != "" {
		json.Unmarshal([]byte(ids_str), &ids)
		return ids
	}
	var relationData []*models.ChatGroupRelation
	if err := s.DB.Model(&models.ChatGroupRelation{}).Where("group_id = ?", groud_id).Find(&relationData).Error; err != nil {
		return ids // 返回空 map 而不是 nil
	}
	for _, relation := range relationData {
		ids[relation.UserType] = relation.UserID // 移除多余 fmt.Sprintf
	}
	jsonData, _ := json.Marshal(ids)
	utils.SetRedis("chat_group_ids_"+fmt.Sprintf("%d", groud_id), jsonData, 60*24*346)
	return ids
}

// SetChatGroupTop 设置聊天组置顶
func (s *ChatService) SetChatGroupTop(group_id uint, is_top uint) uint {
	if err := s.DB.Model(&models.ChatGroup{}).Where("id = ?", group_id).Update("is_top", is_top).Error; err != nil {
		return 0
	}
	return 1
}

// GetChatGroup 获取聊天组
func (s *ChatService) GetChatGroup(admin_id uint, page, pageSize int) ([]*models.ChatGroupList, int64) {
	var groups []*models.ChatGroup
	var total int64

	// 计算偏移量
	offset := (page - 1) * pageSize

	// 获取总记录数
	if err := s.DB.Model(&models.ChatGroup{}).Where("admin_id = ?", admin_id).Count(&total).Error; err != nil {
		return nil, 0
	}

	if err := s.DB.Where("admin_id = ?", admin_id).Offset(offset).Limit(pageSize).Order("created_at desc,is_top asc").Find(&groups).Error; err != nil {
		return nil, 0
	}
	var list []*models.ChatGroupList
	list = []*models.ChatGroupList{}
	for _, data := range groups {
		var user models.Member
		if err := s.DB.Where("id = ?", data.UserID).First(&user).Error; err != nil {
			continue
		}
		var un_read int64
		// 获取总记未读
		if err := s.DB.Model(&models.ChatHistory{}).Where("group_id = ?", data.ID).Where("status = ?", 0).Count(&un_read).Error; err != nil {
			un_read = 0
		}
		lastmsg := &models.ChatHistory{}
		if err := s.DB.Where("group_id = ?", data.ID).Order("created_at desc").First(&lastmsg).Error; err != nil {
			lastmsg = &models.ChatHistory{}
		}
		// log.Printf("lastmsg: %+v", lastmsg)
		lastmsgData := models.ChatHistoryList{
			ID:        lastmsg.ID,
			GroupID:   lastmsg.GroupID,
			UserID:    lastmsg.UserID,
			UserType:  lastmsg.UserType,
			Content:   lastmsg.Content,
			Type:      lastmsg.Type,
			Status:    lastmsg.Status,
			CreatedAt: lastmsg.CreatedAt,
		}
		/*
			    AdminID   uint   `json:"admin_id"`
				ManageID  uint   `json:"manage_id"`
				UserID    uint   `json:"user_id"`
				HeadImg   string `json:"head_img"`
				Username  string `json:"username"`
				UnRead    uint   `json:"un_read"`
		*/
		update_at := lastmsgData.CreatedAt
		if lastmsgData.Type == "image" {
			lastmsgData.Content = "【图片】"
		} else if lastmsgData.Type == "video" {
			lastmsgData.Content = "【视频】"
		} else if lastmsgData.Type == "audio" {
			lastmsgData.Content = "【音频】"
		} else if lastmsgData.Type == "text" {
			lastmsgData.Content = utils.StripTags(lastmsgData.Content)
			if len(lastmsgData.Content) > 30 {
				lastmsgData.Content = utils.StrSubLength(lastmsgData.Content, 30) + "..."
			}
		}
		// log.Printf("update_at %v", update_at)
		if update_at == 0 {
			update_at = data.UpdatedAt
		}
		list = append(list, &models.ChatGroupList{
			ID:           data.ID,
			AdminID:      data.AdminID,
			ManageID:     data.ManageID,
			UserID:       data.UserID,
			HeadImg:      user.HeadImg,
			Username:     user.NickName,
			Email:        user.Email,
			Phone:        user.Phone,
			UnRead:       uint(un_read),
			IsTop:        data.IsTop,
			LastMsg:      lastmsgData,
			UpdatedAt:    update_at,
			UpdatedAtStr: time.Unix(update_at, 0).Format("01-02 15:04"),
		})
		//根据UpdatedAt字段排序 list
		list = utils.ArraySortByField(list, "UpdatedAt", "desc")
	}
	return list, total
}

// ReadMessage 读取聊天记录
func (s *ChatService) ReadMessage(groud_id uint) error {
	return s.DB.Model(&models.ChatHistory{}).Where("group_id = ?", groud_id).Where("status = ?", 0).Update("status", 1).Error
}

/*
添加聊天记录
*/
func (s *ChatService) AddChatHistory(message models.ChatHistoryCreate) (uint, error) {

	/*
		GroupID uint   `json:"group_id"`
		AdminID uint   `json:"admin_id"`
		UserID  uint   `json:"user_id"`
		Content string `json:"content"`
		Type    string `json:"type"`
		Status  uint8  `json:"status"`
	*/
	addData := &models.ChatHistory{
		GroupID:  message.GroupID,
		UserID:   message.UserID,
		UserType: message.UserType,
		Content:  message.Content,
		Type:     message.Type,
		Status:   message.Status,
	}
	if err := s.DB.Create(addData).Error; err != nil {
		return 0, err
	}
	return addData.ID, nil
}

// DelChatHistory 删除聊天记录
func (s *ChatService) DelChatHistory(where string) ([]uint, error) {
	ids := []uint{}
	return ids, s.DB.Where(where).Delete(&models.ChatHistory{}).Error
}

// GetChatHistoryList 获取聊天记录
func (s *ChatService) GetChatHistoryList(where string, page, pageSize int) ([]*models.ChatHistoryList, int64, error) {
	var groups []*models.ChatHistory
	var total int64

	// 计算偏移量
	offset := (page - 1) * pageSize

	// 获取总记录数
	if err := s.DB.Model(&models.ChatHistory{}).Where(where).Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 获取分页数据
	if err := s.DB.Where(where).Offset(offset).Limit(pageSize).Order("id DESC").Find(&groups).Error; err != nil {
		return nil, 0, err
	}
	var list []*models.ChatHistoryList
	list = []*models.ChatHistoryList{}
	for _, data := range groups {
		NickName, HeadImg := s.GetNickId(data.UserID, data.UserType)
		list = append(list, &models.ChatHistoryList{
			ID:           data.ID,
			GroupID:      data.GroupID,
			UserID:       data.UserID,
			NickName:     NickName,
			HeadImg:      HeadImg,
			UserType:     data.UserType,
			Content:      data.Content,
			Type:         data.Type,
			Status:       data.Status,
			CreatedAt:    data.CreatedAt,
			CreatedAtStr: time.Unix(data.CreatedAt, 0).Format("2006-01-02 15:04:05"),
		})
	}
	//设置消息已读
	if err := s.DB.Model(&models.ChatHistory{}).Where(where).Update("status", 1).Error; err != nil {
		return nil, 0, err
	}
	return list, total, nil
}

// GetNickId 获取昵称和头像
func (s *ChatService) GetNickId(id uint, user_type string) (string, string) {
	var NickName string
	var HeadImg string
	NickName = ""
	HeadImg = ""
	user_json := utils.GetRedis(fmt.Sprintf("%s%d", user_type, id))
	if user_json != "" {
		user_data := models.Member{}
		if err := json.Unmarshal([]byte(user_json), &user_data); err != nil {
			return NickName, HeadImg
		}
		NickName = user_data.NickName
		HeadImg = user_data.HeadImg
	}
	if user_type == "admin" {
		var admin models.AuthUser
		if err := s.DB.Where("id = ?", id).First(&admin).Error; err != nil {
			return NickName, HeadImg
		}
		NickName = admin.Realname
		HeadImg = admin.Avatar
		NickHead := UserNickHead{NickName: NickName, HeadImg: HeadImg}
		NickHeadJson, _ := json.Marshal(NickHead)
		utils.SetRedis(fmt.Sprintf("%s%d", user_type, id), NickHeadJson, 3600)
	} else {
		var member models.Member
		if err := s.DB.Where("id = ?", id).First(&member).Error; err != nil {
			return NickName, HeadImg
		}
		NickName = member.NickName
		HeadImg = member.HeadImg
		NickHead := UserNickHead{NickName: NickName, HeadImg: HeadImg}
		NickHeadJson, _ := json.Marshal(NickHead)
		utils.SetRedis(fmt.Sprintf("%s%d", user_type, id), NickHeadJson, 3600)
	}

	return NickName, HeadImg
}
